package ThreadDemo;

import java.util.concurrent.PriorityBlockingQueue;

/**
 * 定时器
 */
public class TreadDemo12 {
    /**
     *创建一个任务类，这个任务包含干的东西和时间
     */
    static class Tast implements Comparable<Tast>{
        private Runnable commend;
        private long time;

        public Tast(Runnable commend, long time) {
            this.commend = commend;
            this.time = time+System.currentTimeMillis();
        }
        public void RUN(){
            commend.run();
        }

        @Override
        public int compareTo(Tast o) {
            return (int) (this.time-o.time);
        }
    }

    /**
     * 创建一个timer类，里面放基本的运行大纲
     */
    static class timer{
        //创建一个优先级堵塞队列
        private PriorityBlockingQueue <Tast>queue=new PriorityBlockingQueue();
        Object locker=new Object();
        //创建一个任务
        public void schedule(Runnable runnable,long delay) {
            Tast tast = new Tast(runnable, delay);
            queue.put(tast);
            //插入一个任务是让线程看一下队首元素的时间是多少
            synchronized (locker) {
                locker.notify();
            }
        }

        public timer() {
            Thread thread=new Thread(new Runnable() {
                @Override
                public void run() {
                    while(true){
                        //取出队首元素判断时间有没有到
                        try {
                            Tast tast=queue.take();
                            if(tast.time>System.currentTimeMillis()){
                                queue.put(tast);
                                synchronized (locker){
                                    locker.wait(tast.time - System.currentTimeMillis());
                                }
                                }else {
                                //时间到了就开始执行
                                tast.RUN();
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            break;
                        }

                    }
                }
            });
            thread.start();
        }
    }

    public static void main(String[] args) {
        timer t=new timer();
        System.out.println("开始" );
        t.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello");
                t.schedule(this,2000);
            }
        },2000);

    }
}
